//
//  BQListViewModel.m
//  BeeQuick
//
//  Created by AaronWei on 2017/7/9.
//  Copyright © 2017年 BecomeRich. All rights reserved.
//

#import "BQListViewModel.h"
#import "BQAccountManager.h"
#import "BQCategoryModel.h"
#import "BQProductModel.h"

@interface BQListViewModel ()

@property (copy, nonatomic) NSArray<BQCategoryModel *> *categories;

@end

@implementation BQListViewModel

+ (instancetype)sharedViewModel {
    
    static id instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [self new];
        
    });
    
    return instance;
    
}

- (instancetype)init {
    
    if (self = [super init]) {
        [self loadData];
    }
    
    return self;
    
}

- (void)loadData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    [parameters setValue:@"5" forKey:@"call"];
    
    [[BQAccountManager sharedInstance] POSTWithUrlString:supermarket_url parameters:parameters success:^(id responseObject) {
        
        NSDictionary *dict = responseObject[@"data"];
        
        NSArray *dataArray = dict[@"categories"];
        
        NSDictionary *productDict = dict[@"products"];
        
        self.categories = [NSArray yy_modelArrayWithClass:[BQCategoryModel class] json:dataArray];
        
        for (BQCategoryModel *model in self.categories) {
            NSLog(@"%@", model.id);
            
            model.products = [NSArray yy_modelArrayWithClass:[BQProductModel class] json:productDict[model.id]];
        }
        
        if (self.successBlock) {
            
            self.successBlock(self.categories);
            
        }
        
    } failure:^(NSError *error) {
        NSLog(@"%@", error);
    }];
    
}

@end
